package service

import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"strconv"
)

//@author: heyibo
//@function: GetJumpServerTree
//@description: 获取持续集成项目树
//@return: err error, menus []model.JumpServerTree
func GetJumpServerTree(username string) (err error, menus []model.JumpServerTree) {
	var jump model.JumpServerTree
	jump.Id = 0
	jump.Label = "我的服务器"
	var jumps []model.JumpServerUser
	err = global.GVA_DB.Where("user_name = ?",username).Find(&jumps).Error
	var  TwoChildren []model.JumpServerTree
	for _, v := range jumps {
		var p model.JumpServerTree
		p.Id = v.ID
		p.Label = v.SshIpAddress
		TwoChildren =append(TwoChildren,p)
	}
	jump.Children = TwoChildren
	menus = append(menus,jump)
	return err, menus
}

//@author: heyibo
//@function: CreateLogicSshClient
//@description: 获取持续集成项目树
//@return: err error, client model.LoginSshClient
func GetLogicSshClient(id float64,uuid string) (clientInfo SshClientInfo, err error){
	var jumps model.JumpServerUser
	err = global.GVA_DB.Model(&model.JumpServerUser{}).Where("id = ?",id).First(&jumps).Error
	if err !=nil {
		return clientInfo, errors.New("查询服务器失败")
	}
	port,_ :=strconv.Atoi(jumps.SshPort)
	clientInfo.Username =  jumps.UserName
	clientInfo.SshUser = jumps.SshUser
	clientInfo.IpAddress =jumps.SshIpAddress
	clientInfo.Port = port
	clientInfo.Password = jumps.SshPassword
	clientInfo.sshType = jumps.SshType
	clientInfo.sshKey = jumps.SshKey
	clientInfo.isAdmin = CheckUserToken(uuid)
	clientInfo.ProxyUser = jumps.ProxyUser
	clientInfo.ProxySshType = jumps.ProxySshType
	clientInfo.ProxyPassword = jumps.ProxyPassword
	clientInfo.ProxyHost = jumps.ProxyHost
	clientInfo.ProxySshKey = jumps.ProxySshKey
	proxyPort,_ :=strconv.Atoi(jumps.ProxyPort)
	clientInfo.ProxyPort = proxyPort
	if jumps.XShellProxy == "connect" {
		clientInfo.isProxy = false
	}else {
		clientInfo.isProxy = true
	}
	return
}


//@author: heyibo
//@function: CheckUserToken
//@description: 验证是否合法用户
//@return: true
func CheckUserToken(token string) bool {
	var total int64
	err :=global.GVA_DB.Where("uuid = ?", token).Find(&model.SysUser{}).Count(&total).Error
	if err != nil {
		errors.New("查询用户出错！")
	}
	if total > 0 {
		return true
	}
	return false
}
func MustSshFilterGroup() (g model.SshFilterGroup) {
	var filter []model.JumpServerCmdFilter
	err :=global.GVA_DB.Model(&model.JumpServerCmdFilter{}).Find(&filter).Error
	if err != nil {
		errors.New("查询规则表失败！")
	}
	g = model.SshFilterGroup{}
    g.Filters = filter
	return g
}
